import json
import datetime

#对单个模型操作
def model_to_dict(model, fields=None,exclude_fileds=None):
    """
    将Flask SQLAlchemy的模型对象转换为字典类型
    :param: model : 模型对象
    :param: fields : 需要获取的字段列表，默认为 None，获取全部字段
    :param: exclude_fields: 排除的字段
    :return: 返回字典类型
    """
    '1、获取所有列名'
    columns = [column.name for column in model.__table__.columns]
    # 排除掉relationships 设置的反向查询字段
    relations = getattr(model.__class__, '__mapper__').relationships
    exclude_cols = [rel.key for rel in relations]
    # print(exclude_cols,'要剔除的反向查询字段')
    # 拿到所有列名-排除的列名
    cols = set(columns) - set(exclude_cols)
    all_fields = list(cols)

    '2、指定要的字段'
    if fields:
        temp = []
        for field in fields:
            if field in all_fields:
                temp.append(field)
        all_fields = fields

    '3、指定不用的字段'
    if not fields and exclude_fileds:
        #排除掉在
        all_fields = list(set(all_fields)-set(exclude_fileds))

    obj_dict = {}
    '4、获取到对于的数据'
    for field in all_fields:
        if field not in model.__dict__:
            continue

        value = model.__dict__[field]
        #1、对时间字段进行操作
        if isinstance(value, datetime.datetime):
            #字段类型是datetime的，格式化
            value = value.strftime('%Y-%m-%d %H:%M:%S')
        if isinstance(value,datetime.date):
            #字段类型是date的，格式化
            value = value.strftime('%Y-%m-%d')
        #2、将所有可以进行序列化的进行序列化
        if isinstance(value,str):
            try:
                t = value
                value = json.loads(value)
                if isinstance(value,(int,float)):
                    value = t
            except Exception as _:
                pass

        obj_dict[field] = value

    return obj_dict

#对数据集操作
def model_to_dict_list(queryset,fields=None,exclude_fileds=None):

    ret = []
    for obj in queryset:
        dic = model_to_dict(obj,fields=fields,exclude_fileds=exclude_fileds)
        ret.append(dic)
    return ret